package newtank.network.client.handler;

import com.alibaba.fastjson.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import newtank.TankClientFrame;
import server.netty.GpcDataPackage;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lijiahao
 * @since 2022/1/28
 */
public class RouterClientDataHandler extends SimpleChannelInboundHandler<GpcDataPackage>  {

    /**
     * 根据不同的code 不同的包处理
     */
    private static final Map<Integer, DataHandler<?>> DATA_HANDLER_CODE_MAP = new HashMap<>();

    static {
        DATA_HANDLER_CODE_MAP.put(1, new EnvironmentDataHandler(TankClientFrame.getInstance()));
        DATA_HANDLER_CODE_MAP.put(10, new MoveDataHandler(TankClientFrame.getInstance()));
        DATA_HANDLER_CODE_MAP.put(20, new ShootDataHandler(TankClientFrame.getInstance()));
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GpcDataPackage gpcDataPackage) throws Exception {
        int code = gpcDataPackage.getCode();
        DataHandler<?> handler = DATA_HANDLER_CODE_MAP.getOrDefault(code, null);
        System.out.println(code + "接收到数据包: "+ JSON.toJSONString(gpcDataPackage));
        if(handler == null) {
            throw new NullPointerException("不支持的数据包类型");
        }
        handler.handle(gpcDataPackage);
    }
}
